﻿using System.ComponentModel;
using System.Reflection;

namespace Common.Core.Enums
{
    /// <summary>
    /// 枚举扩展
    /// </summary>
    public static class EnumExte
    {
        /// <summary>
        /// 获取枚举变量值的描述信息Description
        /// </summary>
        /// <param name="obj">枚举变量</param>
        /// <returns>返回描述信息</returns>
        public static string GetDesc(this Enum obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            try
            {
                Type _enumType = obj.GetType();
                FieldInfo fi = _enumType.GetField(Enum.GetName(_enumType, obj));
                DescriptionAttribute dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));

                if (dna != null && !string.IsNullOrEmpty(dna.Description))
                {
                    return dna.Description;
                }
            }
            catch { }
            //return obj.ToString();
            return string.Empty;
        }

        /// <summary>
        /// 获取枚举键值
        /// </summary>
        /// <param name="obj">枚举变量</param>
        /// <returns>返回枚举键值</returns>
        public static string GetKey(this Enum obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            return Enum.GetName(obj.GetType(), obj);
        }

        /// <summary>
        /// 获取枚举键值
        /// </summary>
        /// <param name="obj">枚举变量</param>
        /// <returns>返回枚举键值</returns>
        public static int GetValue(this Enum obj)
        {
            if (obj == null)
            {
                return default(int);
            }
            return (int)Enum.Parse(obj.GetType(), obj.ToString());
        }
    }
}
